/*
 * Copyright 2005-2006 the original authors and www.opengoss.org community.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.opengoss.web.internal.jetty;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.handler.ContextHandlerCollection;
import org.opengoss.web.core.IWebContainer;
import org.opengoss.web.core.IWebPlugin;
/**
 * A web container implementation based on Jetty.
 *
 * @author Ery Lee(ery.lee@gmail.com)
 * @version 1.0 2006-11-20
 * @since 1.0
 */
public class WebContainer extends ContextHandlerCollection 
	implements IWebContainer {

	static final Log log = LogFactory.getLog(WebContainer.class);

	private Map<String, WebPluginHandler> handlerMap 
		= new HashMap<String, WebPluginHandler>();

	public WebContainer() {
	}
	/*
	 * (non-Javadoc)
	 * @see org.opengoss.web.core.IWebContainer#add(org.opengoss.web.core.IWebPlugin)
	 */
	public void add(IWebPlugin webPlugin) throws Exception {
		String contextPath = webPlugin.getContext().getPluginURI();
		if (handlerMap.get(contextPath) != null) {
			log.warn("The web plugin has been existed! contextPath=" + contextPath);
			return;
		}
		WebPluginHandler wPluginHandler = new WebPluginHandler(this, webPlugin);
		addHandler(wPluginHandler);
		mapContexts();
		wPluginHandler.start();
		handlerMap.put(contextPath, wPluginHandler);
	}
	/*
	 * (non-Javadoc)
	 * @see org.opengoss.web.core.IWebContainer#remove(org.opengoss.web.core.IWebPlugin)
	 */
	public void remove(IWebPlugin webPlugin) throws Exception {
		String contextPath = webPlugin.getContext().getPluginURI();
		WebPluginHandler wPluginHandler = handlerMap.get(contextPath);
		if (wPluginHandler != null) {
			wPluginHandler.stop();
			removeHandler(wPluginHandler);
			mapContexts();
			handlerMap.remove(contextPath);
		}
	}

}
